package com.ctshk.rpc.order.custom.service.impl;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.utils.CharUtil;
import com.ctshk.rpc.custom.dto.trip.*;
import com.ctshk.rpc.custom.json.ContactTelephoneJson;
import com.ctshk.rpc.order.custom.code.CollectionRefundWayIdCode;
import com.ctshk.rpc.order.custom.code.SeriesOrderTouristOtherFeeFeeTypeCode;
import com.ctshk.rpc.order.custom.dto.order.CustomOrderTouristOtherFeeDTO;
import com.ctshk.rpc.order.custom.dto.tourist.*;
import com.ctshk.rpc.order.custom.entity.*;
import com.ctshk.rpc.order.custom.excel.ExcelData;
import com.ctshk.rpc.order.custom.mapper.*;
import com.ctshk.rpc.order.custom.req.tourist.*;
import com.ctshk.rpc.order.custom.vo.ContactPhoneJson;
import com.ctshk.rpc.order.custom.vo.ExcelTemp;
import com.ctshk.rpc.order.custom.vo.TouristCollectionFeeJson;
import com.ctshk.rpc.system.dto.*;
import com.ctshk.rpc.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.NumberConstant;
import com.ctshk.common.enums.StrConstant;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.common.vo.MainDataCount;
import com.ctshk.rpc.custom.req.quotation.TouristTypeDTO;
import com.ctshk.rpc.custom.req.trip.CustomizedTripScheduleDTO;
import com.ctshk.rpc.custom.req.trip.TripScheduleAmountStatisticsReq;
import com.ctshk.rpc.custom.req.trip.TripScheduleTouristCountReq;
import com.ctshk.rpc.custom.service.ICustomizedQuotationTouristTypeService;
import com.ctshk.rpc.custom.service.ICustomizedTripScheduleAmountStatisticsService;
import com.ctshk.rpc.custom.service.ICustomizedTripScheduleCollectionTouristFeeService;
import com.ctshk.rpc.custom.service.ICustomizedTripScheduleService;
import com.ctshk.rpc.custom.service.ICustomizedTripScheduleTouristCountService;
import com.ctshk.rpc.order.custom.code.GenderCode;
import com.ctshk.rpc.order.custom.dto.order.CustomOrderTouristCollectionDTO;
import com.ctshk.rpc.order.custom.req.order.CustomOrderIdReq;
import com.ctshk.rpc.order.custom.req.schedule.TripScheduleInfoReq;
import com.ctshk.rpc.order.custom.service.ICustomizedOrderDiscountService;
import com.ctshk.rpc.order.custom.service.ICustomizedOrderTouristInfoService;
import com.ctshk.rpc.order.custom.service.ICustomizedOrderTouristPriceService;
import com.ctshk.rpc.order.custom.vo.AreaPhone;
import com.ctshk.rpc.system.enums.MessageBusinessType;
import com.ctshk.rpc.system.enums.MessageSource;
import com.ctshk.rpc.system.req.AreaQueryIdReq;
import com.ctshk.rpc.system.req.SysMessageReq;

/**
 * <p>
 * 游客信息 服务实现类
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-02-22
 */
@DubboService
public class CustomizedOrderTouristInfoServiceImpl extends ServiceImpl<CustomizedOrderTouristInfoMapper, CustomizedOrderTouristInfo> implements ICustomizedOrderTouristInfoService {

    @DubboReference
    private ICustomizedQuotationTouristTypeService touristTypeService;
    @DubboReference
    private ICustomizedTripScheduleCollectionTouristFeeService tripScheduleCollectionTouristFeeService;
    @DubboReference
    private ICustomizedTripScheduleService tripScheduleService;
    @DubboReference
    private ISysUserService sysUserService;
    @DubboReference
    private ISysDepartmentService sysDepartmentService;
    @DubboReference
    private IMainDataTouristTypeService mainDataTouristTypeService;
    @DubboReference
    private ICustomizedTripScheduleAmountStatisticsService tripScheduleAmountStatisticsService;
    @DubboReference
    private ICustomizedTripScheduleTouristCountService tripScheduleTouristCountService;
    @Autowired
    private ICustomizedOrderDiscountService orderDiscountService;
    @Autowired
    private ICustomizedOrderTouristInfoService orderTouristInfoService;
    @Autowired
    private ICustomizedOrderTouristPriceService orderTouristPriceService;
    @DubboReference
    private ISystemMessageService systemMessageService;
    @DubboReference
    private ISysAreaService sysAreaService;
    @DubboReference
    private IMainDataTableService mainDataTableService;


    @Autowired
    private CustomizedOrderTouristInfoMapper orderTouristInfoMapper;
    @Autowired
    private CustomizedOrderAmountStatisticsMapper orderAmountStatisticsMapper;
    @Autowired
    private CustomizedOrderMapper orderMapper;
    @Autowired
    private CustomizedOrderTouristOtherFeeMapper orderTouristOtherFeeMapper;
    @Autowired
    private CustomizedOrderTouristFeeAdjustMapper orderTouristFeeAdjustMapper;
    @Autowired
    private CustomizedOrderTouristPriceMapper orderTouristPriceMapper;
    @Autowired
    private CustomizedOrderTouristVisaMapper orderTouristVisaMapper;
    @Autowired
    CustomizedOrderTouristRoomMapper customizedOrderTouristRoomMapper;
    @Autowired
    CustomizedOrderTouristGroupMapper customizedOrderTouristGroupMapper;
    @Autowired
    CustomizedOrderTouristCertificateMapper customizedOrderTouristCertificateMapper;
    @Autowired
    private CustomizedOrderCollectionMapper orderCollectionMapper;
    /*@Autowired
    private RedisTemplate<String, Object> redisTemplate;*/


    /**
     * 旅客信息列表
     *
     * @param req
     * @return
     */
    @Override
    public PageResponse<CustomOrderTouristInfoDTO> list(CustomOrderIdReq req) {
        IPage<CustomOrderIdReq> page = new Page<>(req.getPageNo(), req.getPageSize());
        IPage<CustomOrderTouristInfoDTO> iPage = orderTouristInfoMapper.selectListBySelective(page, req);
        PageResponse<CustomOrderTouristInfoDTO> pageResponse = new PageResponse<>(iPage.getRecords(),
                iPage.getCurrent() == 1,
                iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()),
                iPage.getTotal(), iPage.getCurrent(),
                iPage.getSize());
        return pageResponse;
    }

    /**
     * 编辑旅客信息
     *
     * @param req
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result edit(CustomOrderTouristInfoEditReq req) {
        CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(req.getId());
        if (touristInfo == null || Objects.equals(touristInfo.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4001);
        }
        Long orderId = touristInfo.getOrderId();
        //是否锁定
        if (touristInfo.getLockStatus() != null && touristInfo.getLockStatus().intValue() == NumberConstant.ONE.getValue()){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4054);
        }
        //    touristInfo = EntityUtil.copy(req, CustomizedOrderTouristInfo.class);
        touristInfo.setGender(req.getGender());
        touristInfo.setNation(req.getNation());
        touristInfo.setNationId(req.getNationId());
        touristInfo.setMobileAreaCode(req.getMobileAreaCode());
        touristInfo.setMobile(req.getMobile());
        touristInfo.setEmail(req.getEmail());
        touristInfo.setRemark(req.getRemark());
        touristInfo.setBirthday(req.getBirthday());
        touristInfo.setPeopleType(1);
        //是否完善信息
        if (StringUtils.isNotEmpty(req.getCnSurname()) && StringUtils.isNotEmpty(req.getCnName())){
            touristInfo.setCnName(req.getCnName());
            touristInfo.setCnSurname(req.getCnSurname());
            touristInfo.setCnFullname(req.getCnSurname() + req.getCnName());
            touristInfo.setIsFullInfo(1);
        }
        if (StringUtils.isNotEmpty(req.getEnSurname()) && StringUtils.isNotEmpty(req.getEnName())){
            touristInfo.setEnName(req.getEnName());
            touristInfo.setEnSurname(req.getEnSurname());
            touristInfo.setEnFullname(req.getEnSurname() + req.getEnName());
            touristInfo.setIsFullInfo(1);
        }
        touristInfo.setNoshow(2);
        //检查游客类型年龄范围
        if (touristInfo.getPackageId() != null){
            //自由报价
            TouristTypeDTO touristTypeDTO = touristTypeService.queryTouristType(touristInfo.getPackageId(),touristInfo.getMainDataId(), 1);
            if (touristTypeDTO != null){
                //判断出生日期是否合理
                if (!checkBirthday(req.getBirthday(),touristTypeDTO.getAgeBegin(),touristTypeDTO.getAgeEnd())){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4004);
                }
            }
        }else{
            //行程报价
            TouristTypeDTO touristTypeDTO = touristTypeService.queryTouristType(touristInfo.getScheduleId(),touristInfo.getMainDataId(), 2);
            if (touristTypeDTO != null){
                //判断出生日期是否合理
                if (!checkBirthday(req.getBirthday(),touristTypeDTO.getAgeBegin(),touristTypeDTO.getAgeEnd())){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4004);
                }
            }
        }
        //更新代收费用
        AddTouristTripScheduleDTO tripScheduleDTO = tripScheduleService.getAddTouristTripSchedule(touristInfo.getScheduleId(), touristInfo.getMainDataId());
        touristInfo.setCollectionFee(tripScheduleDTO.getColletionFee() == null?BigDecimal.ZERO:tripScheduleDTO.getColletionFee());
        List<TouristCollectionItemDTO> collectionItemList = tripScheduleDTO.getCollectionItemList();
        if (CollectionUtils.isNotEmpty(collectionItemList)){
            //旅客代收费用明细
            List<TouristCollectionFeeJson> collectionFeeJsonList = new ArrayList<>();
            for (TouristCollectionItemDTO itemDTO : collectionItemList){
                TouristCollectionFeeJson collectionFeeJson = EntityUtil.copy(itemDTO,TouristCollectionFeeJson.class);
                collectionFeeJson.setTotalAmount(itemDTO.getTotalAmount().multiply(itemDTO.getExchangeRate()));
                collectionFeeJsonList.add(collectionFeeJson);
            }
            if (collectionFeeJsonList.size() > 0){
                touristInfo.setCollectionFeeJson(JSON.toJSONString(collectionFeeJsonList));
            }
        }
        //证件
        List<CustomOrderTouristInfoAddCertificateReq> certificateList = req.getCertificateList();
        if (CollectionUtils.isNotEmpty(certificateList)){
            touristInfo.setCertificateNumber(certificateList.get(0).getCertificateNumber());
            touristInfo.setCertificateTypeId(certificateList.get(0).getCertificateTypeId());
            touristInfo.setCertificateType(certificateList.get(0).getCertificateType());
            touristInfo.setCertificatePlaceId(certificateList.get(0).getCertificatePlaceId());
            touristInfo.setCertificatePlace(certificateList.get(0).getCertificatePlace());
            if (certificateList.get(0).getCertificateValidDate().isBefore(LocalDate.now())){
                throw new BusinessException(SystemError.CUSTOM_ORDER_4050);
            }
            touristInfo.setCertificateValidDate(certificateList.get(0).getCertificateValidDate());
            if (certificateList.size() >= 2){
                touristInfo.setCertificateNumber2(certificateList.get(1).getCertificateNumber());
                touristInfo.setCertificateTypeId2(certificateList.get(1).getCertificateTypeId());
                touristInfo.setCertificateType2(certificateList.get(1).getCertificateType());
                touristInfo.setCertificatePlaceId2(certificateList.get(1).getCertificatePlaceId());
                touristInfo.setCertificatePlace2(certificateList.get(1).getCertificatePlace());
                if (certificateList.get(1).getCertificateValidDate().isBefore(LocalDate.now())){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4050);
                }
                touristInfo.setCertificateValidDate2(certificateList.get(1).getCertificateValidDate());
                if (certificateList.size() == 3){
                    touristInfo.setCertificateNumber3(certificateList.get(2).getCertificateNumber());
                    touristInfo.setCertificateTypeId3(certificateList.get(2).getCertificateTypeId());
                    touristInfo.setCertificateType3(certificateList.get(2).getCertificateType());
                    touristInfo.setCertificatePlaceId3(certificateList.get(2).getCertificatePlaceId());
                    touristInfo.setCertificatePlace3(certificateList.get(2).getCertificatePlace());
                    if (certificateList.get(2).getCertificateValidDate().isBefore(LocalDate.now())){
                        throw new BusinessException(SystemError.CUSTOM_ORDER_4050);
                    }
                    touristInfo.setCertificateValidDate3(certificateList.get(2).getCertificateValidDate());
                }
            }
        }
        if (req.getIsApplyAll().intValue() == NumberConstant.ONE.getValue()){
            //紧急联系人应用全部
            if (StringUtils.isBlank(req.getEmergencyContactName()) || StringUtils.isBlank(req.getEmergencyMobileAreaCode()) || StringUtils.isBlank(req.getEmergencyMobile())){
                throw new BusinessException(SystemError.CUSTOM_ORDER_4005);
            }
            //批量更新紧急联系人
            orderTouristInfoMapper.applyEmergencyAll(orderId,req.getEmergencyContactName(),req.getEmergencyMobileAreaCode(),req.getEmergencyMobile());
        }else{
            touristInfo.setEmergencyContactName(req.getEmergencyContactName());
            touristInfo.setEmergencyMobileAreaCode(req.getEmergencyMobileAreaCode());
            touristInfo.setEmergencyMobile(req.getEmergencyMobile());
        }
        int update = orderTouristInfoMapper.updateById(touristInfo);
        if (update <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(touristInfo.getId());
    }

    /**
     * 收款列表
     *
     * @param req
     * @return
     */
    @Override
    public PageResponse<CustomOrderTouristInfoListCollectionDTO> listCollection(CustomOrderIdReq req) {
        IPage<CustomOrderIdReq> pageParam = new Page<>(req.getPageNo(), req.getPageSize());
        IPage<CustomOrderTouristInfoListCollectionDTO> pageResult = orderTouristInfoMapper.selectListCollectionBySelective(pageParam, req);
        List<CustomOrderTouristInfoListCollectionDTO> list = pageResult.getRecords();
        if (CollectionUtils.isNotEmpty(list)){
            list.forEach(dto -> {
                if (StringUtils.isNotBlank(dto.getCollectionFeeJson())){
                    dto.setCollectionFeeDTOList(JSON.parseArray(dto.getCollectionFeeJson(), TouristCollectionFeeJson.class));
                }
                //其他费用列表
                List<CustomOrderTouristOtherFeeDTO> discountList = orderTouristOtherFeeMapper.queryByTourist(dto.getId());
                dto.setOtherFeeDTOList(discountList);
            });
        }
        PageResponse<CustomOrderTouristInfoListCollectionDTO> pageResponse = new PageResponse<>(pageResult.getRecords(),
                pageResult.getCurrent() == 1,
                pageResult.getTotal() <= (pageResult.getCurrent() * pageResult.getSize()),
                pageResult.getTotal(), pageResult.getCurrent(),
                pageResult.getSize());
        return pageResponse;
    }

    /**
     * 团期详情 - 收款明细
     *
     * @param req
     * @return
     */
    @Override
    public List<CustomOrderTouristInfoListCollectionDTO> reciveListBySchedule(TripScheduleInfoReq req) {
        List<CustomOrderTouristInfoListCollectionDTO> reciveList = orderTouristInfoMapper.reciveListBySchedule(req.getScheduleId());
        if (reciveList != null && reciveList.size() > 0){
            reciveList.forEach(recive -> {
                //查询销售
                UserDTO userDto = sysUserService.queryCacheUser(recive.getCreateId());
                if (userDto != null){
                    recive.setSaleUserName(userDto.getFullName());
                    recive.setSaleUserDept(userDto.getDept());
                }
            });
            return reciveList;
        }
        return null;
    }

    /**
     * 旅客详情
     *
     * @param req
     * @return
     */
    @Override
    public Result<CustomOrderTouristInfoDetailDTO> detail(CustomOrderTouristIdReq req) {
        CustomizedOrderTouristInfo touristInfo = getById(req.getId());
        if (touristInfo == null || Objects.equals(touristInfo.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4001);
        }
        CustomOrderTouristInfoDetailDTO dto = EntityUtil.copy(touristInfo, CustomOrderTouristInfoDetailDTO.class);
        //证件信息
        List<CustomOrderTouristInfoDetailCertificateDTO> certificateDTOList = new ArrayList<>();
        if (touristInfo.getCertificateType() != null || touristInfo.getCertificateNumber() != null
                || touristInfo.getCertificateValidDate() != null || touristInfo.getCertificatePlace() != null) {
            CustomOrderTouristInfoDetailCertificateDTO certificateDTO = new CustomOrderTouristInfoDetailCertificateDTO();
            certificateDTO.setCertificateTypeId(touristInfo.getCertificateTypeId());
            certificateDTO.setCertificateType(touristInfo.getCertificateType());
            certificateDTO.setCertificateNumber(touristInfo.getCertificateNumber());
            certificateDTO.setCertificateValidDate(touristInfo.getCertificateValidDate());
            certificateDTO.setCertificatePlaceId(touristInfo.getCertificatePlaceId());
            certificateDTO.setCertificatePlace(touristInfo.getCertificatePlace());
            certificateDTOList.add(certificateDTO);
        }
        if (touristInfo.getCertificateType2() != null || touristInfo.getCertificateNumber2() != null
                || touristInfo.getCertificateValidDate2() != null || touristInfo.getCertificatePlace2() != null) {
            CustomOrderTouristInfoDetailCertificateDTO certificateDTO = new CustomOrderTouristInfoDetailCertificateDTO();
            certificateDTO.setCertificateTypeId(touristInfo.getCertificateTypeId2());
            certificateDTO.setCertificateType(touristInfo.getCertificateType2());
            certificateDTO.setCertificateNumber(touristInfo.getCertificateNumber2());
            certificateDTO.setCertificateValidDate(touristInfo.getCertificateValidDate2());
            certificateDTO.setCertificatePlaceId(touristInfo.getCertificatePlaceId2());
            certificateDTO.setCertificatePlace(touristInfo.getCertificatePlace2());
            certificateDTOList.add(certificateDTO);
        }
        if (touristInfo.getCertificateType3() != null || touristInfo.getCertificateNumber3() != null
                || touristInfo.getCertificateValidDate3() != null || touristInfo.getCertificatePlace3() != null) {
            CustomOrderTouristInfoDetailCertificateDTO certificateDTO = new CustomOrderTouristInfoDetailCertificateDTO();
            certificateDTO.setCertificateTypeId(touristInfo.getCertificateTypeId3());
            certificateDTO.setCertificateType(touristInfo.getCertificateType3());
            certificateDTO.setCertificateNumber(touristInfo.getCertificateNumber3());
            certificateDTO.setCertificateValidDate(touristInfo.getCertificateValidDate3());
            certificateDTO.setCertificatePlaceId(touristInfo.getCertificatePlaceId3());
            certificateDTO.setCertificatePlace(touristInfo.getCertificatePlace3());
            certificateDTOList.add(certificateDTO);
        }
        dto.setCertificateList(certificateDTOList);
        return Result.success(dto);
    }

    /**
     * 删除旅客
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result delete(CustomOrderTouristIdReq req) {
        //获取旅客
        CustomizedOrderTouristInfo touristInfo = getById(req.getId());
        if (touristInfo == null || Objects.equals(touristInfo.getIsDeleted(),NumberConstant.ONE.getValue())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4001);
        }
        //已付款过，不能删除
        if (touristInfo.getPayStatus().intValue() != NumberConstant.ONE.getValue()) {
            throw new BusinessException(SystemError.CUSTOM_ORDER_4006);
        }
        //订单统计
        QueryWrapper<CustomizedOrderAmountStatistics> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().eq(CustomizedOrderAmountStatistics::getOrderId, touristInfo.getOrderId());
        CustomizedOrderAmountStatistics statistics = orderAmountStatisticsMapper.selectOne(queryWrapper2);
        statistics.setTotalReceivables(touristInfo.getTotalReceivables().subtract(touristInfo.getTotalReceivables()));
        statistics.setTotalPaidIn(statistics.getTotalPaidIn().subtract(touristInfo.getTotalPaidIn()));
        statistics.setRemainingReceivables(statistics.getRemainingReceivables().subtract(touristInfo.getRemainingReceivables()));
        statistics.setRefundAmount(statistics.getRefundAmount().subtract(touristInfo.getRefundAmount()));
        statistics.setTotalTourFee(statistics.getTotalTourFee().subtract(touristInfo.getGroupFee()));
        statistics.setCollectionFee(statistics.getCollectionFee().subtract(touristInfo.getCollectionFee()));
        statistics.setAdjustmentCost(statistics.getAdjustmentCost().subtract(touristInfo.getAdjustmentCost()));
        statistics.setOtherAmount(statistics.getOtherAmount().subtract(touristInfo.getOtherAmount()));
        statistics.setReceiptedAmount(statistics.getReceiptedAmount().subtract(touristInfo.getReceiptedAmount()));
        //查询旅客折扣金额
        BigDecimal discountAmount = orderDiscountService.sumAmountByTourist(touristInfo.getOrderId(),touristInfo.getId());
        if (discountAmount != null && discountAmount.compareTo(BigDecimal.ZERO) > 0){
            //有折扣记录(总应收和剩余应收回滚折扣金额)
            statistics.setTotalReceivables(statistics.getTotalReceivables().add(discountAmount));
            statistics.setRemainingReceivables(statistics.getRemainingReceivables().add(discountAmount));
            //清空旅客订单折扣记录
            boolean blDiscount = orderDiscountService.cleanByTourist(touristInfo.getOrderId(), touristInfo.getId(), req.getUserId());
            if (!blDiscount){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //清空旅客签证记录
        QueryWrapper<CustomizedOrderTouristVisa> visaQueryWrapper = new QueryWrapper<>();
        visaQueryWrapper.eq("order_id",touristInfo.getOrderId());
        visaQueryWrapper.eq("tourist_id",req.getId());
        orderTouristVisaMapper.delete(visaQueryWrapper);
        //更新订单统计
        int updateOrderStatistics = orderAmountStatisticsMapper.updateById(statistics);
        if (updateOrderStatistics <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //更新团期金额统计
        Integer updateAmountStatistics = tripScheduleAmountStatisticsService.updateAmountStatistics(
                new TripScheduleAmountStatisticsReq(touristInfo.getScheduleId(), touristInfo.getGroupFee(), 1, req.getUserId(), 2));
        if (updateAmountStatistics <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //处理团期统计
        dealTripScheduleStatictics(touristInfo,req.getUserId());
        //改为已删除
        touristInfo.setIsDeleted(1);
        touristInfo.setModifiedId(req.getUserId());
        touristInfo.setGmtModified(LocalDateTime.now());
        updateById(touristInfo);
        //旅客是否全被删除
        QueryWrapper<CustomizedOrderTouristInfo> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.lambda().eq(CustomizedOrderTouristInfo::getOrderId, touristInfo.getOrderId());
        List<CustomizedOrderTouristInfo> dbTouristInfoList = orderTouristInfoMapper.selectList(queryWrapper4);
        boolean isDeleteAll = true;
        for (CustomizedOrderTouristInfo dbTouristInfo : dbTouristInfoList) {
            if (dbTouristInfo.getIsDeleted().intValue() == NumberConstant.ONE.getValue()) {
                isDeleteAll = false;
                break;
            }
        }
        //更新套餐人数统计
        if (touristInfo.getPackageId() != null){
            //自由报价
            Integer updatePeopleCount = orderTouristPriceMapper.updateByOrder(touristInfo.getOrderId(),touristInfo.getPackageId(),touristInfo.getMainDataId(),req.getUserId());
            if (updatePeopleCount <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        //旅客全被删除并且订单未收款
        if (isDeleteAll && statistics.getTotalPaidIn().compareTo(new BigDecimal(0)) <= 0) {
            CustomizedOrder order = orderMapper.selectById(touristInfo.getOrderId());
            order.setModifiedId(req.getUserId());
            order.setIsDeleted(1);
            int update = orderMapper.updateById(order);
            if (update <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
            //取消订单后的处理
            dealAfterOrderCancel(touristInfo.getOrderId(), req.getUserId(),order.getScheduleId(), statistics.getId(), order.getTotalPeople(),statistics.getTotalTourFee());
        }
        return Result.success(touristInfo.getId());
    }

    /**
     * 取消订单后的处理
     * @param orderId
     * @param userId
     * @param scheduleId
     * @param statisticsId
     * @param totalPeople
     * @param totalTourFee
     */
    private void dealAfterOrderCancel(Long orderId, Long userId, Long scheduleId, Long statisticsId,Integer totalPeople,BigDecimal totalTourFee) {
        //团期旅客类型统计回滚
        List<MainDataCount> list =  orderTouristInfoMapper.queryCountByMainDataId(orderId);
        boolean blCount = tripScheduleTouristCountService.rollBackCount(list,scheduleId,userId);
        //清空订单折扣记录
        boolean blDiscount = orderDiscountService.cleanByOrder(orderId,userId);
        //清空关联旅客
        boolean blTourist = orderTouristInfoService.cleanByOrder(orderId,userId);
        //清空订单统计
        int del = orderAmountStatisticsMapper.deleteById(statisticsId);
        //清空报价
        boolean blPrice = orderTouristPriceService.cleanByOrder(orderId,userId);
        //团期金额统计回滚
        boolean rollBack = tripScheduleAmountStatisticsService.rollBackStatistics(scheduleId, totalPeople,totalTourFee,userId);
        if (!blDiscount || del <= 0 || !blTourist || !blPrice || !rollBack || !blCount){
            throw new BusinessException(SystemError.SYS_437);
        }
    }


    /**
     * 添加旅客
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(CustomOrderTouristInfoAddReq req) {
        System.out.println("添加旅客req =====>>> " + req.toString());
        //添加旅客时获取团期信息
        AddTouristTripScheduleDTO scheduleDTO = tripScheduleService.getAddTouristTripSchedule(req.getScheduleId(), req.getMainDataId());
        if (scheduleDTO.getTouristDTO() == null){
            throw new BusinessException(SystemError.CUSTOM_3009);
        }
        if (Objects.equals(scheduleDTO.getLockStatus(),1) || Objects.equals(scheduleDTO.getGroupStatus(),4)){
            //财务锁定和已完团不可再添加旅客
            throw new BusinessException(SystemError.CUSTOM_3017);
        }
        //校验是否可添加
        if (!checkAddEnable(scheduleDTO.getTouristDTO().getPeopleNum(),req.getOrderId(),req.getMainDataId())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4007);
        }
        //校验出生日期是否符合该旅客类型
        if (!checkBirthday(req.getBirthday(),scheduleDTO.getTouristDTO().getAgeBegin(),scheduleDTO.getTouristDTO().getAgeEnd())){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4004);
        }
        CustomizedOrderTouristInfo touristInfo = EntityUtil.copy(req, CustomizedOrderTouristInfo.class);
        //是否完善信息
        if ((StringUtils.isNotBlank(req.getCnSurname()) && StringUtils.isNotBlank(req.getCnName())) || StringUtils.isNotBlank(req.getEnSurname()) && StringUtils.isNotBlank(req.getEnName())){
            touristInfo.setIsFullInfo(1);
        }else{
            throw new BusinessException(SystemError.CUSTOM_ORDER_4003);
        }
        touristInfo.setBuyInsurance(0);
        //团费
        BigDecimal groupFee = BigDecimal.ZERO;
        //代收费用
        BigDecimal collectionFee = BigDecimal.ZERO;
        //查询套餐(自由报价)
        if (req.getTouristPriceId() != null){
            CustomizedOrderTouristPrice orderTouristPrice = orderTouristPriceMapper.selectById(req.getTouristPriceId());
            if (orderTouristPrice != null){
                groupFee = orderTouristPrice.getSinglePrice();
                groupFee = tripScheduleService.getScheduleAddAmount(groupFee, req.getScheduleId(), req.getUserId());
                if (orderTouristPrice.getPackageId() != null){
                    touristInfo.setPackageId(orderTouristPrice.getPackageId());
                    touristInfo.setPackageName(orderTouristPrice.getPackageName());
                }
                //更新旅客套餐记录
                orderTouristPrice.setTotalPrice(orderTouristPrice.getTotalPrice().add(groupFee));
                orderTouristPrice.setPeopleNum(orderTouristPrice.getPeopleNum() + 1);
                orderTouristPrice.setModifiedId(req.getUserId());
                int updatePackage = orderTouristPriceMapper.updateById(orderTouristPrice);
                if (updatePackage <= 0){
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
        }else{
            //行程报价
            CustomizedTripScheduleDTO tripSchedule = tripScheduleService.queryByScheduleId(req.getScheduleId());
            //行程报价-总单价
            BigDecimal quoteTotalSinglePrice = tripSchedule.getQuoteTotalSinglePrice();
            groupFee = tripScheduleService.getScheduleAddAmount(quoteTotalSinglePrice,req.getScheduleId(),req.getUserId());
        }
        //查询代收费用
        if (scheduleDTO.getColletionFee() != null){
            collectionFee = scheduleDTO.getColletionFee();
        }
        List<TouristCollectionItemDTO> collectionItemList = scheduleDTO.getCollectionItemList();
        if (CollectionUtils.isNotEmpty(collectionItemList)){
            //旅客代收费用明细
            List<TouristCollectionFeeJson> collectionFeeJsonList = new ArrayList<>();
            for (TouristCollectionItemDTO itemDTO : collectionItemList){
                TouristCollectionFeeJson collectionFeeJson = EntityUtil.copy(itemDTO,TouristCollectionFeeJson.class);
                collectionFeeJson.setTotalAmount(itemDTO.getTotalAmount().multiply(itemDTO.getExchangeRate()).setScale(2,BigDecimal.ROUND_HALF_UP));
                collectionFeeJsonList.add(collectionFeeJson);
            }
            if (collectionFeeJsonList.size() > 0){
                touristInfo.setCollectionFeeJson(JSON.toJSONString(collectionFeeJsonList));
            }
        }
        //新增旅客
        touristInfo.setId(SnowflakeIdWorker.nextId());
        touristInfo.setScheduleId(req.getScheduleId());
        touristInfo.setNoshow(2);
        touristInfo.setPeopleType(1);
        if (StringUtils.isNotBlank(req.getCnSurname()) && StringUtils.isNotBlank(req.getCnName())){
            touristInfo.setCnFullname(req.getCnSurname() + req.getCnName());
        }
        if (StringUtils.isNotBlank(req.getEnSurname()) && StringUtils.isNotBlank(req.getEnName())){
            touristInfo.setEnFullname(req.getEnSurname() + req.getEnName());
        }
        touristInfo.setGroupFee(groupFee);
        touristInfo.setLockStatus(0);
        touristInfo.setPayStatus(1);
        touristInfo.setTotalReceivables(groupFee.add(collectionFee));
        touristInfo.setTotalPaidIn(BigDecimal.ZERO);
        touristInfo.setRefundAmount(BigDecimal.ZERO);
        touristInfo.setCollectionFee(collectionFee);
        touristInfo.setAdjustmentCost(BigDecimal.ZERO);
        touristInfo.setOtherAmount(BigDecimal.ZERO);
        touristInfo.setReceiptedAmount(BigDecimal.ZERO);
        touristInfo.setRemainingReceivables(touristInfo.getTotalReceivables());
        touristInfo.setCreateId(req.getUserId());
        //证件
        List<CustomOrderTouristInfoAddCertificateReq> certificateList = req.getCertificateList();
        if (CollectionUtils.isNotEmpty(certificateList)){
            touristInfo.setCertificateNumber(certificateList.get(0).getCertificateNumber());
            touristInfo.setCertificateTypeId(certificateList.get(0).getCertificateTypeId());
            touristInfo.setCertificateType(certificateList.get(0).getCertificateType());
            touristInfo.setCertificatePlaceId(certificateList.get(0).getCertificatePlaceId());
            touristInfo.setCertificatePlace(certificateList.get(0).getCertificatePlace());
            if (certificateList.get(0).getCertificateValidDate().isBefore(LocalDate.now())){
                throw new BusinessException(SystemError.CUSTOM_ORDER_4050);
            }
            touristInfo.setCertificateValidDate(certificateList.get(0).getCertificateValidDate());
            if (certificateList.size() >= 2){
                touristInfo.setCertificateNumber2(certificateList.get(1).getCertificateNumber());
                touristInfo.setCertificateTypeId2(certificateList.get(1).getCertificateTypeId());
                touristInfo.setCertificateType2(certificateList.get(1).getCertificateType());
                touristInfo.setCertificatePlaceId2(certificateList.get(1).getCertificatePlaceId());
                touristInfo.setCertificatePlace2(certificateList.get(1).getCertificatePlace());
                if (certificateList.get(1).getCertificateValidDate().isBefore(LocalDate.now())){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4050);
                }
                touristInfo.setCertificateValidDate2(certificateList.get(1).getCertificateValidDate());
                if (certificateList.size() == 3){
                    touristInfo.setCertificateNumber3(certificateList.get(2).getCertificateNumber());
                    touristInfo.setCertificateTypeId3(certificateList.get(2).getCertificateTypeId());
                    touristInfo.setCertificateType3(certificateList.get(2).getCertificateType());
                    touristInfo.setCertificatePlaceId3(certificateList.get(2).getCertificatePlaceId());
                    touristInfo.setCertificatePlace3(certificateList.get(2).getCertificatePlace());
                    if (certificateList.get(2).getCertificateValidDate().isBefore(LocalDate.now())){
                        throw new BusinessException(SystemError.CUSTOM_ORDER_4050);
                    }
                    touristInfo.setCertificateValidDate3(certificateList.get(2).getCertificateValidDate());
                }
            }
        }
        int insert = orderTouristInfoMapper.insert(touristInfo);
        if (insert <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //更新费用信息
        if (groupFee.compareTo(BigDecimal.ZERO) > 0){
            //更新订单
            CustomizedOrder order = orderMapper.selectById(req.getOrderId());
            order.setTotalPrice(order.getTotalPrice().add(groupFee).add(collectionFee));
            order.setTotalPeople(order.getTotalPeople() + 1);
            order.setModifiedId(req.getUserId());
            int updateOrder = orderMapper.updateById(order);
            //更新订单统计
            QueryWrapper<CustomizedOrderAmountStatistics> amountStatisticsWrapper = new QueryWrapper<>();
            amountStatisticsWrapper.eq("order_id",req.getOrderId());
            CustomizedOrderAmountStatistics amountStatistics = orderAmountStatisticsMapper.selectOne(amountStatisticsWrapper);
            amountStatistics.setTotalTourFee(amountStatistics.getTotalTourFee().add(groupFee));
            amountStatistics.setTotalReceivables(amountStatistics.getTotalReceivables().add(groupFee).add(collectionFee));
            amountStatistics.setCollectionFee(amountStatistics.getCollectionFee().add(collectionFee));
            amountStatistics.setRemainingReceivables(amountStatistics.getRemainingReceivables().add(groupFee).add(collectionFee));
            int updateAmountStatistics = orderAmountStatisticsMapper.updateById(amountStatistics);

            if (updateOrder <= 0 || updateAmountStatistics <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
            //处理团期统计
            dealTripScheduleStatictics(touristInfo,req.getUserId());
        }
        if (Objects.equals(req.getIsApplyAll(),1)){
            //紧急联系人应用全部
            if (StringUtils.isNotBlank(req.getEmergencyContactName()) && StringUtils.isNotBlank(req.getEmergencyMobileAreaCode()) && StringUtils.isNotBlank(req.getEmergencyMobile())){
                throw new BusinessException(SystemError.CUSTOM_ORDER_4005);
            }
            //批量更新紧急联系人
            orderTouristInfoMapper.applyEmergencyAll(touristInfo.getOrderId(),req.getEmergencyContactName(),req.getEmergencyMobileAreaCode(),req.getEmergencyMobile());
        }else{
            touristInfo.setEmergencyContactName(req.getEmergencyContactName());
            touristInfo.setEmergencyMobileAreaCode(req.getEmergencyMobileAreaCode());
            touristInfo.setEmergencyMobile(req.getEmergencyMobile());
            int update = orderTouristInfoMapper.updateById(touristInfo);
            if (update <= 0){
                throw new BusinessException(SystemError.SYS_408);
            }
        }
        return Result.success(touristInfo.getId());
    }

    /**
     * 处理团期统计
     * @param touristInfo
     * @param userId
     */
    private void dealTripScheduleStatictics(CustomizedOrderTouristInfo touristInfo, Long userId) {
        //更新团期金额统计
        Integer updateStatistics = tripScheduleAmountStatisticsService.updateAmountStatistics(
                new TripScheduleAmountStatisticsReq(touristInfo.getScheduleId(), touristInfo.getGroupFee(), 1, userId, 1));
        if (updateStatistics <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        //更新团期旅客类型统计
        List<TripScheduleTouristCountDTO> countDTOS = tripScheduleTouristCountService.queryBySchedule(touristInfo.getScheduleId());
        if (countDTOS != null && countDTOS.size() > 0){
            List<TripScheduleTouristCountReq> countReqList = new ArrayList<>();
            for (TripScheduleTouristCountDTO countDTO : countDTOS){
                if (countDTO.getTouristTypeId().longValue() == touristInfo.getMainDataId().longValue()){
                    TripScheduleTouristCountReq countReq = new TripScheduleTouristCountReq();
                    countReq.setId(countDTO.getId());
                    countReq.setOrderPeople(countDTO.getOrderPeople()-1);
                    countReq.setModifiedId(userId);
                    countReqList.add(countReq);
                }
            }
            if (countReqList.size() > 0){
                boolean bl = tripScheduleTouristCountService.batchUpdate(countReqList);
                if (!bl){
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
        }
    }

    /**
     * 打印發票预览
     *
     * @param req
     * @param currentUser
     * @return
     */
    @Override
    public Result<CustomOrderTouristInfoPreviewInvoiceDTO> previewInvoice(CustomOrderTouristInfoPreviewInvoiceReq req, TokenUser currentUser) {
        CustomizedOrder order = orderMapper.selectById(req.getOrderId());
        if (order == null || Objects.equals(order.getIsDeleted(),1)){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
        }
        if (req.getTouristIdList().size() <= 0) {
            return Result.failed(SystemError.SYS_409);
        }
        Long firstTouristId = req.getTouristIdList().get(0);
        CustomizedOrderTouristInfo firstTouristInfo = orderTouristInfoMapper.selectById(firstTouristId);
        if (firstTouristInfo == null  || Objects.equals(firstTouristInfo.getIsDeleted(), NumberConstant.ONE.getValue())) {
            return Result.failed(SystemError.SYS_411);
        }
        CustomizedTripScheduleDTO tripSchedule = tripScheduleService.queryByScheduleId(order.getScheduleId());
        CustomOrderTouristInfoPreviewInvoiceDTO dto = new CustomOrderTouristInfoPreviewInvoiceDTO();
        dto.setEnquiryNo(CharUtil.getRandomStr(6));
        dto.setTripName(tripSchedule.getName());
        if (tripSchedule.getDeliveryDays() != null){
            LocalDate dueDate = tripSchedule.getGmtCreate().plusDays(tripSchedule.getDeliveryDays().longValue()).toLocalDate();
            dto.setDueDate(dueDate);
        }
        //團體/旅客姓名/To
        dto.setCnSurname(firstTouristInfo.getCnSurname());
        dto.setCnName(firstTouristInfo.getCnName());
        dto.setEnSurname(firstTouristInfo.getEnSurname());
        dto.setEnName(firstTouristInfo.getEnName());

        //订单联系人
        dto.setContactCnSurname(order.getContactCnSurname());
        dto.setContactCnName(order.getContactCnName());
        dto.setContactEnSurname(order.getContactEnSurname());
        dto.setContactEnName(order.getContactEnName());
        dto.setContactEmail(order.getContactEmail());
        if (StringUtils.isNotBlank(order.getContactTelephones())){
            try{
                ContactPhoneJson contactPhoneJson = JSON.parseObject(order.getContactTelephones(), ContactPhoneJson.class);
                dto.setContactPhone(contactPhoneJson.getAreaCode()+" "+contactPhoneJson.getPhones());
            }catch (Exception e){
                List<ContactPhoneJson> contactPhoneJsonList = JSON.parseArray(order.getContactTelephones(), ContactPhoneJson.class);
                ContactPhoneJson contactPhoneJson = contactPhoneJsonList.get(0);
                dto.setContactPhone(contactPhoneJson.getAreaCode()+" "+contactPhoneJson.getPhones());
            }
        }
        /*if (StringUtils.isNotBlank(order.getContactTelephones())) {
            List<ContactTelephoneJson> telephoneJsonList = JSON.parseArray(order.getContactTelephones(), ContactTelephoneJson.class);
            ContactTelephoneJson telephoneJson = telephoneJsonList.get(0);
            dto.setContactAreaCode(telephoneJson.getContactTelAreaCode());
            dto.setContactPhone(telephoneJson.getContactTelephones());
        }*/
        //销售人员
        UserDTO createUser = sysUserService.queryCacheUser(order.getCreateId());
        if (createUser != null) {
            //應付日期/Due Date：門市編號+員工編號+月日4位+時分秒6位
            dto.setInvoiceNumber(createUser.getDeptCode()+createUser.getEmployeeNumber()+DateUtil.fmt(LocalDateTime.now(),"MMddHHmmss"));
            dto.setOrderUsername(createUser.getFullName());
            dto.setOrderAreaCode(createUser.getMobileAreaCode());
            dto.setOrderPhone(createUser.getMobile());
        }
        //当前用户
        dto.setCurrentUsername(currentUser.getNickname());
        dto.setCurrentDate(LocalDate.now());
        //摘要
        List<TouristCollectionFeeInfoDTO> touristCollectionFeeInfoList = new ArrayList<>();
        //总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (Long id : req.getTouristIdList()) {
            CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(id);
            //摘要
            TouristCollectionFeeInfoDTO collectionFeeInfoDTO = new TouristCollectionFeeInfoDTO();
            collectionFeeInfoDTO.setCnName(touristInfo.getCnFullname());
            collectionFeeInfoDTO.setEnName(touristInfo.getEnFullname());
            collectionFeeInfoDTO.setTouristTotalAmount(touristInfo.getTotalReceivables());
            totalAmount = totalAmount.add(touristInfo.getTotalReceivables());
            List<TouristCollectionFeeJson> groupFeeList = new ArrayList<>();
            //团费
            TouristCollectionFeeJson groupFee = new TouristCollectionFeeJson();
            groupFee.setProjectName("團費");
            groupFee.setTotalAmount(touristInfo.getGroupFee());
            groupFee.setAdjustType(1);
            groupFeeList.add(groupFee);
            collectionFeeInfoDTO.setGroupFee(groupFeeList);
            if (StringUtils.isNotBlank(touristInfo.getCollectionFeeJson())){
                //代收费用
                List<TouristCollectionFeeJson> collectionFeeList = JSON.parseArray(touristInfo.getCollectionFeeJson(), TouristCollectionFeeJson.class);
                if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(collectionFeeList)){
                    collectionFeeList.forEach(collectionFeeJson -> {
                        collectionFeeJson.setAdjustType(1);
                    });
                    collectionFeeInfoDTO.setCollectionFee(collectionFeeList);
                }
            }
            //调整费用
            List<TouristCollectionFeeJson> adjustFeeList = orderTouristFeeAdjustMapper.queryByTourist(touristInfo.getId());
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(adjustFeeList)){
                collectionFeeInfoDTO.setAdjustFee(adjustFeeList);
            }
            //其他费用
            List<TouristCollectionFeeJson> otherFeeList = orderTouristOtherFeeMapper.selectByTourist(touristInfo.getId());
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(otherFeeList)){
                collectionFeeInfoDTO.setOtherFee(otherFeeList);
            }
            collectionFeeInfoDTO.setIsWillExpire(0);
            //证件是否快到期
            if (touristInfo.getCertificateValidDate() != null){
                int toDays = (int) Duration.between(LocalDateTime.now(), DateUtil.parse(DateUtil.fmtLocalDate(touristInfo.getCertificateValidDate(),"yyyy-MM-dd"))).toDays();
                if (toDays <= 72){
                    collectionFeeInfoDTO.setIsWillExpire(1);
                }
            }
            if (touristInfo.getCertificateValidDate2() != null){
                int toDays = (int)Duration.between(LocalDateTime.now(), DateUtil.parse(DateUtil.fmtLocalDate(touristInfo.getCertificateValidDate2(),"yyyy-MM-dd"))).toDays();
                if (toDays <= 72){
                    collectionFeeInfoDTO.setIsWillExpire(1);
                }
            }
            if (touristInfo.getCertificateValidDate3() != null){
                int toDays = (int)Duration.between(LocalDateTime.now(), DateUtil.parse(DateUtil.fmtLocalDate(touristInfo.getCertificateValidDate3(),"yyyy-MM-dd"))).toDays();
                if (toDays <= 72){
                    collectionFeeInfoDTO.setIsWillExpire(1);
                }
            }
            touristCollectionFeeInfoList.add(collectionFeeInfoDTO);
        }
        dto.setTouristCollectionFeeInfoList(touristCollectionFeeInfoList);
        dto.setTotalAmount(totalAmount);
        return Result.success(dto);
    }

    /**
     * 校验是否可添加
     *
     * @param req
     * @return
     */
    @Override
    public Result<Boolean> checkAdd(TouristInfoCheckAddReq req) {
        //获取团期旅客类型信息
        TripScheduleTouristDTO tourist = tripScheduleService.getTripScheduleTourist(req.getScheduleId(), req.getTouristTypeId());
        if (tourist == null){
            throw new BusinessException(SystemError.CUSTOM_3009);
        }
        //校验是否可添加
        return Result.success(checkAddEnable(tourist.getPeopleNum(),req.getOrderId(),req.getTouristTypeId()));
    }


    /**
     * 收款明细
     *
     * @param req
     * @return
     */
    @Override
    public List<CustomOrderTouristCollectionDTO> reciveList(CustomOrderTouristIdReq req) {
        List<CustomOrderTouristCollectionDTO> reciveList = orderTouristInfoMapper.reciveListByTourist(req.getId());
        if (reciveList != null){
            reciveList.forEach(collectionDTO -> {
                try {
                    UserDTO userDTO = sysUserService.queryCacheUser(collectionDTO.getCreateId());
                    if (userDTO != null){
                        collectionDTO.setReciveName(userDTO.getFullName());
                        collectionDTO.setReciveDept(userDTO.getDept());
                    }
                }catch (Exception e){
                    throw new BusinessException(SystemError.SYS_417);
                }
            });
            return reciveList;
        }
        return null;
    }

    /**
     * 清空订单旅客信息
     *
     * @param orderId
     * @param userId
     * @return
     */
    @Override
    public boolean cleanByOrder(Long orderId, Long userId) {
        QueryWrapper<CustomizedOrderTouristInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId);
        queryWrapper.eq("is_deleted",0);
        List<CustomizedOrderTouristInfo> list = orderTouristInfoMapper.selectList(queryWrapper);
        if (list != null && list.size() > 0){
            list.forEach(touristInfo -> {
                touristInfo.setModifiedId(userId);
                touristInfo.setIsDeleted(1);
            });
            return updateBatchById(list);
        }
        return true;
    }


    /**
     * 旅客名单 - show/noShow切换
     *
     * @param req
     * @return
     */
    @Override
    public Result noShow(CustomOrderTouristNoShowReq req) {
        if (CollectionUtils.isNotEmpty(req.getIds())){
            for (Long id : req.getIds()){
                CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(id);
                if (touristInfo == null){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4001);
                }
                int noShow = 0;
                if (touristInfo.getNoshow() == null || touristInfo.getNoshow().intValue() == NumberConstant.ZERO.getValue()){
                    //show -> noShow
                    noShow = 1;
                }
                touristInfo.setNoshow(noShow);
                touristInfo.setModifiedId(req.getUserId());
                int update = orderTouristInfoMapper.updateById(touristInfo);
                if (update <= 0){
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
        }
        return Result.success(req.getIds());
    }

    /**
     * 旅客名单 - 锁定状态切换
     *
     * @param req
     * @return
     */
    @Override
    public Result changeLock(CustomOrderTouristNoShowReq req) {
        if (CollectionUtils.isNotEmpty(req.getIds())) {
            for (Long id : req.getIds()) {
                CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(id);
                if (touristInfo == null){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4001);
                }
                touristInfo.setLockStatus(req.getLockStatus());
                touristInfo.setModifiedId(req.getUserId());
                int update = orderTouristInfoMapper.updateById(touristInfo);
                if (update <= 0){
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
        }
        return Result.success(req.getIds());
    }


    /**
     * 旅客名单 - 登记
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result checkIn(CustomOrderTouristCheckInReq req) {
        if (CollectionUtils.isNotEmpty(req.getTouristIdList())){
            for (Long id : req.getTouristIdList()){
                CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(id);
                if (touristInfo == null){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4001);
                }
                if (touristInfo.getBuyVisa() == null || touristInfo.getBuyVisa().intValue() != NumberConstant.ONE.getValue()){
                    //签证非托我司办理
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4036);
                }
                CustomizedOrder order = orderMapper.selectById(touristInfo.getOrderId());
                if (order == null){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4008);
                }
                //获取签证详情
                QueryWrapper<CustomizedOrderTouristVisa> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("tourist_id",id);
                queryWrapper.eq("order_id",touristInfo.getOrderId());
                CustomizedOrderTouristVisa touristVisa = orderTouristVisaMapper.selectOne(queryWrapper);
                if (touristVisa == null){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4037);
                }
                if (touristVisa.getSignOutStatus() == null || touristVisa.getSignOutStatus().intValue() != NumberConstant.THREE.getValue()){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4038);
                }
                //更新旅客签证
                touristVisa.setNeedSupplyInfo(1);
                touristVisa.setMissingCertificate(req.getMissingCertificate());
                touristVisa.setAdviseSubmitTime(req.getAdviseSubmitTime());
                int update = orderTouristVisaMapper.updateById(touristVisa);
                if (update <= 0){
                    throw new BusinessException(SystemError.SYS_437);
                }
                //发送系统通知
                SysMessageReq addReq = new SysMessageReq();
                addReq.setType(2);
                addReq.setBusinessType(MessageBusinessType.CHECK_IN_SUCCESS.getCode());
                addReq.setSource(MessageSource.PRODUCT_CENTER.getMsg());
                addReq.setTitle("旅客["+touristInfo.getId()+"]登记");
                addReq.setBusinessId(touristVisa.getId());
                addReq.setBusinessOrderNo(order.getOrderNumber());
                addReq.setReceivingUserId(order.getCreateId());
                addReq.setSendingTime(LocalDateTime.now());
                try {
                    systemMessageService.add(addReq, req.getUserId());
                }catch (Exception e){
                    throw new BusinessException(SystemError.SYS_419);
                }
            }
        }
        return Result.success(req.getTouristIdList());
    }

    /**
     * 旅客名单 - 送签
     *
     * @param req
     * @return
     */
    @Override
    public Result sendVisa(CustomOrderTouristSendVisaReq req) {
        if (CollectionUtils.isNotEmpty(req.getTouristIdList())){
            for (Long id : req.getTouristIdList()){
                CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(id);
                if (touristInfo == null){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4001);
                }
                //获取签证详情
                QueryWrapper<CustomizedOrderTouristVisa> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("tourist_id",id);
                queryWrapper.eq("order_id",touristInfo.getOrderId());
                CustomizedOrderTouristVisa touristVisa = orderTouristVisaMapper.selectOne(queryWrapper);
                if (touristVisa == null){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4037);
                }
                if (touristInfo.getBuyVisa() == null || touristInfo.getBuyVisa().intValue() != NumberConstant.ONE.getValue()){
                    //签证非托我司办理
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4036);
                }
                if (touristVisa.getCollectionStatus() == null || touristVisa.getCollectionStatus().intValue() != NumberConstant.TWO.getValue()){
                    //证件未收齐
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4039);
                }
                if (touristVisa.getSignOutStatus() == null || touristVisa.getSignOutStatus().intValue() != NumberConstant.THREE.getValue()){
                    throw new BusinessException(SystemError.CUSTOM_ORDER_4038);
                }
                //更新
                touristVisa.setSignOutStatus(4);
                touristVisa.setSendTime(req.getAdviseSubmitTime());
                int update = orderTouristVisaMapper.updateById(touristVisa);
                if (update <= 0){
                    throw new BusinessException(SystemError.SYS_437);
                }
            }
        }

        return Result.success(req.getTouristIdList());
    }

    /**
     * 旅客名单 - 出签成功
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result signOutSuccess(CustomOrderTouristSignOutSuccessReq req) {
        for (Long touristId : req.getTouristIdList()) {
            QueryWrapper<CustomizedOrderTouristVisa> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(CustomizedOrderTouristVisa::getOrderId, req.getOrderId());
            queryWrapper.lambda().eq(CustomizedOrderTouristVisa::getTouristId, touristId);
            CustomizedOrderTouristVisa dbVisa = orderTouristVisaMapper.selectOne(queryWrapper);
            if (dbVisa == null || !Objects.equals(dbVisa.getSignOutStatus(), 4)) {
                continue;
            }
            CustomizedOrderTouristVisa updateObject = EntityUtil.copy(req, CustomizedOrderTouristVisa.class);
            updateObject.setId(dbVisa.getId());
            int update = orderTouristVisaMapper.updateById(updateObject);
            if (update <= 0){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
        return Result.success();
        /*CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(req.getId());
        if (touristInfo == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4001);
        }
        //获取签证详情
        QueryWrapper<CustomizedOrderTouristVisa> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tourist_id",req.getId());
        queryWrapper.eq("order_id",touristInfo.getOrderId());
        CustomizedOrderTouristVisa touristVisa = orderTouristVisaMapper.selectOne(queryWrapper);
        if (touristVisa == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4037);
        }
        if (touristInfo.getBuyVisa() == null || touristInfo.getBuyVisa().intValue() != NumberConstant.ONE.getValue()){
            //签证非托我司办理
            throw new BusinessException(SystemError.CUSTOM_ORDER_4036);
        }
        if (touristVisa.getSignOutStatus() == null || touristVisa.getSignOutStatus().intValue() != NumberConstant.FOUR.getValue()){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4038);
        }
        touristVisa.setSignOutStatus(1);
        touristVisa.setSignOutTrackingNumber(req.getSignOutTrackingNumber());
        touristVisa.setSignOutTime(LocalDateTime.now());
        touristVisa.setSignOutExpressTime(req.getSignOutExpressTime());
        touristVisa.setSignOutReceiptFile(req.getSignOutReceiptFile());
        touristVisa.setSignOutFilesJson(req.getSignOutFilesJson());
        int update = orderTouristVisaMapper.updateById(touristVisa);
        if (update <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(touristVisa.getId());*/
    }

    /**
     * 旅客名单 - 出签失败
     *
     * @param req
     * @return
     */
    /*@Override
    public Result signOutFail(CustomOrderTouristSignOutSuccessReq req) {
        CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(req.getId());
        if (touristInfo == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4001);
        }
        //获取签证详情
        QueryWrapper<CustomizedOrderTouristVisa> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tourist_id",req.getId());
        queryWrapper.eq("order_id",touristInfo.getOrderId());
        CustomizedOrderTouristVisa touristVisa = orderTouristVisaMapper.selectOne(queryWrapper);
        if (touristVisa == null){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4037);
        }
        if (touristInfo.getBuyVisa() == null || touristInfo.getBuyVisa().intValue() != NumberConstant.ONE.getValue()){
            //签证非托我司办理
            throw new BusinessException(SystemError.CUSTOM_ORDER_4036);
        }
        if (touristVisa.getSignOutStatus() == null || touristVisa.getSignOutStatus().intValue() != NumberConstant.FOUR.getValue()){
            throw new BusinessException(SystemError.CUSTOM_ORDER_4038);
        }
        touristVisa.setSignOutStatus(2);
        touristVisa.setSignOutTrackingNumber(req.getSignOutTrackingNumber());
        touristVisa.setSignOutTime(LocalDateTime.now());
        touristVisa.setSignOutExpressTime(req.getSignOutExpressTime());
        touristVisa.setSignOutFilesJson(req.getSignOutFilesJson());
        int update = orderTouristVisaMapper.updateById(touristVisa);
        if (update <= 0){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(touristVisa.getId());
    }*/


    /**
     * 校验是否可添加
     * @param peopleNum
     * @param orderId
     * @param touristTypeId
     * @return
     */
    private boolean checkAddEnable(Integer peopleNum, Long orderId, Long touristTypeId) {
        //统计订单当前类型人数
        QueryWrapper<CustomizedOrderTouristInfo> touristInfoWrapper = new QueryWrapper<>();
        touristInfoWrapper.eq("order_id",orderId);
        touristInfoWrapper.eq("main_data_id",touristTypeId);
        touristInfoWrapper.eq("is_deleted",0);
        Integer currentNum = orderTouristInfoMapper.selectCount(touristInfoWrapper);
        if (peopleNum.intValue() >= currentNum.intValue()){
            return true;
        }
        return false;
    }

    /**
     * 判断出生日期是否合理
     * @param birthday
     * @param ageBegin
     * @param ageEnd
     * @return
     */
    private boolean checkBirthday(LocalDate birthday, Integer ageBegin, Integer ageEnd) {
        //当前年龄
        int age = birthday.until(LocalDate.now()).getYears();
        //是否合理
        if (age >= ageBegin && age <= ageEnd){
            return true;
        }
        return false;
    }

    /**
     * 旅客名单
     */
    @Override
    public PageResponse<CustomOrderTouristNameListDTO> nameList(CustomOrderTouristNameListReq touristNameListReq) {
        Page<CustomOrderTouristNameListDTO> iPage = new Page<>(touristNameListReq.getPageNo(), touristNameListReq.getPageSize());
        IPage<CustomOrderTouristNameListDTO> touristPage = orderTouristInfoMapper.queryTouristList(iPage,touristNameListReq);

        if (CollectionUtils.isEmpty(touristPage.getRecords())) {
            return PageResponse.empty(touristPage.getCurrent());
        }

        List<CustomOrderTouristNameListDTO> listDTOS = new ArrayList<>();
        CustomOrderTouristNameListDTO nameListDTO ;
        for (CustomOrderTouristNameListDTO record : touristPage.getRecords()) {
            nameListDTO = new CustomOrderTouristNameListDTO();
            BeanUtils.copyProperties(record,nameListDTO);

            if (record.getCreateId() != null){
                UserDTO userDTO = sysUserService.queryCacheUser(record.getCreateId());
                nameListDTO.setCreateUserName(userDTO.getFullName());
                nameListDTO.setCreateUserDept(userDTO.getDept());
            }

            //证件文件路径列表
            List<String> certificatePathList = customizedOrderTouristCertificateMapper.queryPathListByTourist(record.getId());
            nameListDTO.setCertificatePathList(certificatePathList);

            listDTOS.add(nameListDTO);
        }
        return new PageResponse<>(listDTOS, touristPage.getCurrent() == 1
                , touristPage.getTotal() <= (touristPage.getCurrent() * touristPage.getSize())
                , touristPage.getTotal(), touristPage.getCurrent(), touristPage.getSize());
    }

    /**
     * 旅客分组列表
     */
    @Override
    public PageResponse<CustomOrderTouristRoomGroupDTO> queryList(CustomOrderTouristRoomReq roomReq) {
        Page<CustomOrderTouristRoomGroupDTO> iPage = new Page<>(roomReq.getPageNo(), roomReq.getPageSize());
        IPage<CustomOrderTouristRoomGroupDTO> groupPage = customizedOrderTouristRoomMapper.queryList(iPage,roomReq);
        if(CollectionUtils.isEmpty(groupPage.getRecords())){
            return PageResponse.empty(groupPage.getCurrent());
        }
        List<CustomOrderTouristRoomGroupDTO> dtoList = new ArrayList<>();
        CustomOrderTouristRoomGroupDTO roomGroupDTO;
        for (CustomOrderTouristRoomGroupDTO record : groupPage.getRecords()) {
            roomGroupDTO = new CustomOrderTouristRoomGroupDTO();
            BeanUtils.copyProperties(record,roomGroupDTO);
            if (record.getCreateId() != null){
                UserDTO userDTO = sysUserService.queryCacheUser(record.getCreateId());
                roomGroupDTO.setCreateUserName(userDTO.getFullName());
                roomGroupDTO.setCreateUserDept(userDTO.getDept());
            }
            dtoList.add(roomGroupDTO);
        }
        return new PageResponse<>(dtoList, groupPage.getCurrent() == 1
                , groupPage.getTotal() <= (groupPage.getCurrent() * groupPage.getSize())
                , groupPage.getTotal(), groupPage.getCurrent(), groupPage.getSize());
    }

    /**
     * 查询所有游客分房
     */
    @Override
    public List<CustomOrderTouristRoomDTO> roomList(CustomOrderTouristRoomReq roomReq) {
        List<CustomOrderTouristRoomDTO> dtos = customizedOrderTouristRoomMapper.roomList(roomReq);
        if (CollectionUtils.isNotEmpty(dtos)){
            dtos.forEach(dto -> {
                if (dto.getCreateId() != null){
                    UserDTO userDTO = sysUserService.queryCacheUser(dto.getCreateId());
                    dto.setCreateUserName(userDTO.getFullName());
                    dto.setCreateUserDept(userDTO.getDept());
                }
            });
        }
        return dtos;
    }

    /**
     * 游客分组
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result group(CustomRoomGroupReq req) {
        //1手动分组 2自动分组
        if (Objects.equals(req.getType(),1)){
            if (req.getGroupNo() == null){
                return Result.failed(SystemError.SYS_402);
            }
            //查询分组
            CustomizedOrderTouristGroup group = customizedOrderTouristGroupMapper.selectById(req.getGroupNo());
            if (group == null || Objects.equals(group.getIsDeleted(),1)){
                return Result.failed(SystemError.SYS_411);
            }
            for (Long id : req.getIds()) {
                CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(id);
                if (touristInfo == null || Objects.equals(touristInfo.getIsDeleted(),1)){
                    continue;
                }
                //修改旅客信息
                touristInfo.setGroupId(group.getId());
                touristInfo.setModifiedId(req.getUserId());
                int update = orderTouristInfoMapper.updateById(touristInfo);
                if (update <= 0){
                    return Result.failed(SystemError.SYS_408);
                }
            }
        }else if (Objects.equals(req.getType(),2)){
            LocalDateTime now = LocalDateTime.now();
            List<CustomizedOrderTouristGroup> batchAddList = new ArrayList<>();
            //清空分组记录
            customizedOrderTouristGroupMapper.delBySchedule(req.getScheduleId(), req.getUserId());
            //重置团期旅客groupId
            orderTouristInfoMapper.resetGroupByIdList(req.getScheduleId(), req.getUserId());
            if (req.getQue() == null || Objects.equals(req.getQue(),0)){
                return Result.failed(SystemError.SYS_402);
            }
            //每组多少人
            int groupNumb = Math.floorDiv(req.getIds().size(),req.getQue());
            //余数
            int remainNumber = req.getIds().size() % req.getQue();
            for (int i = 0; i < req.getQue(); i++) {
                for (int j = 0; j < groupNumb; j++) {
                    int a = i * groupNumb + j;
                    Long id = req.getIds().get(a);
                    CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(id);
                    if (touristInfo == null || Objects.equals(touristInfo.getIsDeleted(),1)){
                        continue;
                    }
                    //封装旅客分组参数
                    CustomizedOrderTouristGroup group = packGroupParam(i,touristInfo.getOrderId(),touristInfo.getScheduleId(),req.getUserId(),now);
                    batchAddList.add(group);
                    //修改旅客信息
                    touristInfo.setGroupId(group.getId());
                    touristInfo.setModifiedId(req.getUserId());
                    int update = orderTouristInfoMapper.updateById(touristInfo);
                    if (update <= 0){
                        return Result.failed(SystemError.SYS_408);
                    }
                }
            }
            //判断是否有余数
            if (remainNumber > 0){
                int begin = groupNumb * req.getQue() - 1;
                for (int i = begin; i < req.getIds().size(); i++) {
                    CustomizedOrderTouristInfo touristInfo = orderTouristInfoMapper.selectById(begin);
                    if (touristInfo == null || Objects.equals(touristInfo.getIsDeleted(),1)){
                        continue;
                    }
                    //封装旅客分组参数（分配到第一组）
                    CustomizedOrderTouristGroup group = packGroupParam(1,touristInfo.getOrderId(),touristInfo.getScheduleId(),req.getUserId(),now);
                    batchAddList.add(group);
                    //修改旅客信息
                    touristInfo.setGroupId(group.getId());
                    touristInfo.setModifiedId(req.getUserId());
                    int update = orderTouristInfoMapper.updateById(touristInfo);
                    if (update <= 0){
                        return Result.failed(SystemError.SYS_408);
                    }
                }
            }
            //批量新增分组记录
            if (batchAddList.size() > 0){
                Integer batch = customizedOrderTouristGroupMapper.insertBatchSomeColumn(batchAddList);
                if (batch < batchAddList.size()){
                    return Result.failed(SystemError.SYS_408);
                }
            }
        }
        return Result.success();
    }

    /**
     * 封装旅客分组参数
     * @param i
     * @param orderId
     * @param scheduleId
     * @param userId
     * @param now
     * @return
     */
    private CustomizedOrderTouristGroup packGroupParam(int i, Long orderId, Long scheduleId, Long userId,LocalDateTime now) {
        CustomizedOrderTouristGroup group = new CustomizedOrderTouristGroup();
        group.setId(SnowflakeIdWorker.nextId());
        group.setGroupName(String.valueOf(i + 1));
        group.setSort(i + 1);
        group.setOrderId(orderId);
        group.setScheduleId(scheduleId);
        group.setCreateId(userId);
        group.setGmtCreate(now);
        group.setIsDeleted(0);
        return group;
    }


    /**
     * 游客分房
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateRoom(CustomRoomRoomReq roomReq,Long userId) {
        Long maxRoom = customizedOrderTouristRoomMapper.queryMaxRoom(roomReq.getScheduleId());
        int roomNum = 1;
        if(null != maxRoom){
            roomNum = maxRoom.intValue() + 1;
        }
        if ("1".equalsIgnoreCase(roomReq.getRoomType())) {
            // 分房
            long roomId = SnowflakeIdWorker.nextId();
            List<Long> ids = roomReq.getIds();
            CustomizedOrderTouristInfo customizedOrderTouristInfo = orderTouristInfoMapper.selectById(ids.get(0));
            if(null != customizedOrderTouristInfo){
                CustomizedOrderTouristRoom room = new CustomizedOrderTouristRoom();
                room.setId(roomId);
                room.setRoomNumber(String.valueOf(roomNum));
                room.setOrderId(customizedOrderTouristInfo.getOrderId());
                room.setScheduleId(customizedOrderTouristInfo.getScheduleId());
                room.setCreateId(userId);
                customizedOrderTouristRoomMapper.insert(room);
            }
            // 更新游客表
            for (Long id : ids) {
                QueryWrapper<CustomizedOrderTouristInfo> queryWrapper = new QueryWrapper();
                queryWrapper.eq("id",id);
                CustomizedOrderTouristInfo info = new CustomizedOrderTouristInfo();
                info.setModifiedId(userId);
                info.setRoomId(roomId);
                info.setGmtModified(LocalDateTime.now());
                orderTouristInfoMapper.update(info,queryWrapper);
            }
        } else if ("2".equalsIgnoreCase(roomReq.getRoomType())) {
            // 取消分房 删除游客表中房号
            List<Long> ids = roomReq.getIds();
            if(CollectionUtils.isNotEmpty(ids)){
                for (Long id : ids) {
                    QueryWrapper<CustomizedOrderTouristInfo> wrapper = new QueryWrapper<>();
                    wrapper.eq("id",id);
                    CustomizedOrderTouristInfo info = new CustomizedOrderTouristInfo();
                    info.setModifiedId(userId);
                    info.setGmtModified(LocalDateTime.now());
                    info.setRoomId(0L);
                    orderTouristInfoMapper.update(info,wrapper);
                }
            }
        }
        return Result.success();
    }

    /**
     * 获取团信息
     * @param id
     * @return
     */
    @Override
    public CustomGroupTouristInfoDTO groupInfo(Long id) {
        // 旅行团信息
        CustomGroupTouristInfoDTO touristInfo = new CustomGroupTouristInfoDTO();
        CustomizedTripScheduleDTO scheduleDTO = tripScheduleService.queryByScheduleId(id);
        if(null != scheduleDTO){
            touristInfo.setDepartureDate(scheduleDTO.getDepartureDate());
            touristInfo.setTripNumber(scheduleDTO.getTripNumber());
        }
        // 报名人数
        QueryWrapper<CustomizedOrderTouristInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("schedule_id",id);
        queryWrapper.eq("is_deleted",0);
        List<CustomizedOrderTouristInfo> infos = orderTouristInfoMapper.selectList(queryWrapper);
        // 报名类型人数
        touristInfo.setEnrollNum(infos.size());
        List<CustomGroupTouristInfoDTO> infoDTOS = orderTouristInfoMapper.groupEnrollNum(id);
        if(CollectionUtils.isNotEmpty(infoDTOS)){
            for (int i = 0; i < infoDTOS.size(); i++) {
                if(i==0){
                    CustomGroupTouristInfoDTO dto = infoDTOS.get(0);
                    touristInfo.setEnrollType1(dto.getPeopleType());
                    touristInfo.setEnrollTypeNum1(dto.getPeopleNum());
                }
                if(i==1){
                    CustomGroupTouristInfoDTO dto = infoDTOS.get(1);
                    touristInfo.setEnrollType1(dto.getPeopleType());
                    touristInfo.setEnrollTypeNum1(dto.getPeopleNum());
                }
                if(i==2){
                    CustomGroupTouristInfoDTO dto = infoDTOS.get(2);
                    touristInfo.setEnrollType1(dto.getPeopleType());
                    touristInfo.setEnrollTypeNum1(dto.getPeopleNum());
                }
            }
        }
        return touristInfo;
    }

    /**
     * 根据团期id查询组信息
     *
     * @param id 团期id
     * @return 组信息
     */
    @Override
    public Result<List<CustomOrderTouristGroupDTO>> queryGroup(Long id) {
        QueryWrapper<CustomizedOrderTouristGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomizedOrderTouristGroup::getScheduleId,id);
        queryWrapper.lambda().eq(CustomizedOrderTouristGroup::getIsDeleted,0);
        List<CustomizedOrderTouristGroup> groups = customizedOrderTouristGroupMapper.selectList(queryWrapper);
        if(CollectionUtils.isEmpty(groups)){
            return Result.failed(SystemError.SYS_411);
        }
        List<CustomOrderTouristGroupDTO> groupDTOList = EntityUtil.copyList(groups, CustomOrderTouristGroupDTO.class);
        return Result.success(groupDTOList);
    }

    /**
     * 新增游客分组
     *
     * @param scheduleId 团期id
     * @return 返回值
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addGroup(Long scheduleId,Long userId) {
        QueryWrapper<CustomizedOrderTouristGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CustomizedOrderTouristGroup::getScheduleId,scheduleId);
        queryWrapper.lambda().eq(CustomizedOrderTouristGroup::getIsDeleted,0);
        List<CustomizedOrderTouristGroup> groups = customizedOrderTouristGroupMapper.selectList(queryWrapper);
        Integer count = customizedOrderTouristGroupMapper.selectCount(queryWrapper);
        CustomizedOrderTouristGroup group;
        if(CollectionUtils.isEmpty(groups)){
            group = new CustomizedOrderTouristGroup();
            group.setId(SnowflakeIdWorker.nextId());
            group.setScheduleId(scheduleId);
            group.setGroupName((count+1)+"");
            group.setCreateId(userId);
            group.setIsDeleted(0);
        } else {
            CustomizedOrderTouristGroup touristGroup = groups.get(0);
            Long orderId = touristGroup.getOrderId();
            group = new CustomizedOrderTouristGroup();
            group.setId(orderId);
            group.setScheduleId(scheduleId);
            group.setGroupName((count+1)+"");
            group.setCreateId(userId);
            group.setIsDeleted(0);
        }
        int num = customizedOrderTouristGroupMapper.insert(group);
        if(num<1){
            throw new BusinessException(SystemError.SYS_437);
        }
        return Result.success(group.getId());
    }

    /**
     * 旅客名单-导出分组
     *
     * @param req
     * @return
     */
    @Override
    public ExcelData exportGroup(TripScheduleInfoReq req) {
        //根据团期获取旅客分组列表
        List<CustomOrderTouristRoomGroupDTO> dtoList = customizedOrderTouristRoomMapper.queryBySchedule(req.getScheduleId());
        if (CollectionUtils.isNotEmpty(dtoList)){
            ExcelData data = new ExcelData();
            data.setName(DateUtil.fmt(LocalDateTime.now(),"yyyyMMddHHmmss"));
            List<List<String>> title = new ArrayList();
            //设置Excel表头
            List<String> header = setExcelHeader(1);
            //设置数据
            List<List<Object>> rows = new ArrayList();
            for (CustomOrderTouristRoomGroupDTO dto : dtoList) {
                List<Object> row = new ArrayList();
                row.add(dto.getGroupId());
                row.add(Integer.valueOf(dto.getLockStatus())==1?"已锁定":"未锁定");
                String noShow = "否";
                if (dto.getNoShow() != null && Objects.equals(dto.getNoShow(),1)){
                    noShow = "是";
                }
                row.add(noShow);
                row.add(dto.getEnFullName());
                row.add(dto.getCnFullName());
                row.add(dto.getTouristTypeName());
                row.add(getPayStatusStr(dto.getPayStatus()));
                row.add(dto.getBirthday());
                row.add(getGenderStr(dto.getGender()));
                row.add(dto.getNation());
                row.add(dto.getMobile());
                row.add(dto.getEmail());
                row.add(dto.getOrderNumber());
                row.add(getOrderSourceStr(dto.getOrderSource()));
                UserDTO creater = sysUserService.queryCacheUser(dto.getCreateId());
                row.add(creater.getFullName()+"/"+creater.getDept()+"/n +"+creater.getMobileAreaCode()+creater.getMobile());
                row.add(dto.getEmergencyContactName()+" "+dto.getEmergencyMobileAreaCode()+dto.getEmergencyMobile());
                row.add(dto.getRemark());
                rows.add(row);
            }
            if (rows.size() == 0){
                throw new BusinessException(SystemError.FINANCE_BILL_17023);
            }
            title.add(header);
            data.setTitles(title);
            data.setRows(rows);
            return data;
        }
        return null;
    }

    /**
     * 旅客名单-导出分房
     *
     * @param req
     * @return
     */
    @Override
    public ExcelData exportRoom(TripScheduleInfoReq req) {
        List<CustomOrderTouristRoomDTO> dtos = customizedOrderTouristRoomMapper.queryRoomBySchedule(req);
        if (CollectionUtils.isNotEmpty(dtos)){
            ExcelData data = new ExcelData();
            data.setName(DateUtil.fmt(LocalDateTime.now(),"yyyyMMddHHmmss"));
            List<List<String>> title = new ArrayList();
            //设置Excel表头
            List<String> header = setExcelHeader(2);
            //设置数据
            List<List<Object>> rows = new ArrayList();
            for (CustomOrderTouristRoomDTO dto : dtos) {
                List<Object> row = new ArrayList();
                row.add(dto.getRoomNumber());
                row.add(Integer.valueOf(dto.getLockStatus())==1?"已锁定":"未锁定");
                String noShow = "否";
                if (dto.getNoShow() != null && Objects.equals(dto.getNoShow(),1)){
                    noShow = "是";
                }
                row.add(noShow);
                row.add(dto.getEnFullName());
                row.add(dto.getCnFullName());
                row.add(dto.getTouristTypeName());
                row.add(getPayStatusStr(dto.getPayStatus()));
                row.add(dto.getBirthday());
                row.add(getGenderStr(dto.getGender()));
                row.add(dto.getNation());
                row.add(dto.getMobile());
                row.add(dto.getEmail());
                row.add(dto.getOrderNumber());
                row.add(getOrderSourceStr(dto.getOrderSource()));
                UserDTO creater = sysUserService.queryCacheUser(dto.getCreateId());
                row.add(creater.getFullName()+"/"+creater.getDept()+"/n +"+creater.getMobileAreaCode()+creater.getMobile());
                row.add(dto.getEmergencyContactName()+" "+dto.getEmergencyMobileAreaCode()+dto.getEmergencyMobile());
                row.add(dto.getRemark());
                rows.add(row);
            }
            if (rows.size() == 0){
                throw new BusinessException(SystemError.FINANCE_BILL_17023);
            }
            title.add(header);
            data.setTitles(title);
            data.setRows(rows);
            return data;
        }
        return null;
    }

    /**
     * 旅客名单-导出名单
     *
     * @param req
     * @return
     */
    @Override
    public ExcelData exportTourist(TripScheduleInfoReq req) {
        List<CustomOrderTouristNameListDTO> dtoList = orderTouristInfoMapper.queryListBySchedule(req.getScheduleId());
        if (CollectionUtils.isNotEmpty(dtoList)){
            ExcelData data = new ExcelData();
            data.setName(DateUtil.fmt(LocalDateTime.now(),"yyyyMMddHHmmss"));
            List<List<String>> title = new ArrayList();
            //设置Excel表头
            List<String> header = setExcelHeader2();
            //设置数据
            List<List<Object>> rows = new ArrayList();
            for (CustomOrderTouristNameListDTO dto : dtoList) {
                List<Object> row = new ArrayList();
                row.add(Integer.valueOf(dto.getLockStatus())==1?"已锁定":"未锁定");
                String noShow = "否";
                if (dto.getNoShow() != null && Objects.equals(dto.getNoShow(),1)){
                    noShow = "是";
                }
                row.add(noShow);
                row.add(dto.getEnFullname());
                row.add(dto.getCnFullname());
                row.add(dto.getTouristTypeName());
                row.add(getPayStatusStr(dto.getPayStatus()));
                row.add(dto.getBirthday());
                row.add(getGenderStr(dto.getGender()));
                row.add(dto.getNation());
                row.add(dto.getMobile());
                row.add(dto.getEmail());
                row.add(dto.getOrderNumber());
                row.add(getOrderSourceStr(dto.getOrderSource()));
                UserDTO creater = sysUserService.queryCacheUser(dto.getCreateId());
                row.add(creater.getFullName()+"/"+creater.getDept()+" +"+creater.getMobileAreaCode()+creater.getMobile());
                row.add(dto.getCertificateType());
                row.add(dto.getCertificateNumber());
                row.add(dto.getCertificateValidDate());
                row.add(dto.getCertificateType2());
                row.add(dto.getCertificateNumber2());
                row.add(dto.getCertificateValidDate2());
                row.add(dto.getCertificateType3());
                row.add(dto.getCertificateNumber3());
                row.add(dto.getCertificateValidDate3());
                row.add(dto.getEmergencyContactName()+" "+dto.getEmergencyMobileAreaCode()+dto.getEmergencyMobile());
                row.add(dto.getInternalRemark());
                row.add(dto.getBuyVisa());
                row.add(dto.getCollectionStatus());
                row.add(dto.getSubmitTimeAndNumber());
                row.add(dto.getMakeUpTimeNumber());
                row.add(dto.getSignOutStatus());
                rows.add(row);
            }
            if (rows.size() == 0){
                throw new BusinessException(SystemError.FINANCE_BILL_17023);
            }
            title.add(header);
            data.setTitles(title);
            data.setRows(rows);
            return data;
        }
        return null;
    }

    /**
     * 获取付款状态
     * @param str
     * @return
     */
    public String getPayStatusStr(String str){
        String payStatus = "未付款";
        if ("2".equals(str)){
            payStatus = "待付尾款";
        }else if ("3".equals(str)){
            payStatus = "已付全款";
        }
        return payStatus;
    }

    /**
     * 获取称谓
     * @param str
     * @return
     */
    public String getGenderStr(String str){
        String gender = "先生";
        if ("2".equals(str)){
            gender = "女士";
        }else if ("3".equals(str)){
            gender = "小姐";
        }else if ("4".equals(str)){
            gender = "男童";
        }else if ("5".equals(str)){
            gender = "女童";
        }
        return gender;
    }

    /**
     * 获取订单来源
     * @param str
     * @return
     */
    public String getOrderSourceStr(String str){
        String orderSource = "CPM云平台";
        if ("2".equals(str)){
            orderSource = "CPM代理下单";
        }else if ("3".equals(str)){
            orderSource = "PC官网";
        }else if ("4".equals(str)){
            orderSource = "安卓";
        }else if ("5".equals(str)){
            orderSource = "IOS";
        }else if ("6".equals(str)){
            orderSource = "H5";
        }
        return orderSource;
    }

    /**
     * 设置表头2
     * @return
     */
    private List<String> setExcelHeader2() {
        List<String> header = new ArrayList();
        header.add("狀態");
        header.add("NoShow");
        header.add("英文名");
        header.add("中文名");
        header.add("旅客類型");
        header.add("收款狀態");
        header.add("出生日期");
        header.add("性別");
        header.add("國籍");
        header.add("電話");
        header.add("電郵");
        header.add("銷售單號");
        header.add("渠道來源");
        header.add("所屬銷售");
        header.add("證件類型1");
        header.add("證件編號1");
        header.add("證件有效期1");
        header.add("證件類型2");
        header.add("證件編號2");
        header.add("證件有效期2");
        header.add("證件類型3");
        header.add("證件編號3");
        header.add("證件有效期3");
        header.add("緊急聯繫人");
        header.add("備註");
        header.add("簽證辦理");
        header.add("材料狀態");
        header.add("提交后台时间/运单号");
        header.add("补齐提交资料时间/运单号");
        header.add("簽證狀態");
        return header;
    }

    /**
     * 设置表头
     * @return
     */
    private List<String> setExcelHeader(int type) {
        List<String> header = new ArrayList();
        if (type == 1){
            header.add("分組號");
        }else{
            header.add("分房");
        }
        header.add("狀態");
        header.add("NoShow");
        header.add("英文名");
        header.add("中文名");
        header.add("類型");
        header.add("收款狀態");
        header.add("出生日期");
        header.add("性別");
        header.add("國籍");
        header.add("電話");
        header.add("電郵");
        header.add("銷售單號");
        header.add("渠道來源");
        header.add("所屬銷售");
        header.add("緊急聯繫人");
        header.add("備註");
        return header;
    }

    /**
     * 获取国籍ID
     *
     * @param nation
     * @return
     */
    @Override
    public Long getNationId(String nation) {
        if (StringUtils.isNotBlank(nation)){
            List<AreaDTO> areaDTOS = sysAreaService.esOneLevel(nation);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(areaDTOS)){
                return areaDTOS.get(0).getId();
            }
        }
        return null;
    }

    /**
     * 获取证件类型ID
     *
     * @param stringCellValue
     * @return
     */
    @Override
    public Long getCertificateTypeId(String stringCellValue) {
        List<MainDataRowFieldDataDTO> list = mainDataTableService.groupByDataField(1348475429155237889L,1348477526361763842L);
        for (MainDataRowFieldDataDTO item : list) {
            if (stringCellValue.equals(item.getFieldValue())){
                return item.getId();
            }
        }
        return null;
    }

    /**
     * 导入旅客名单
     *
     * @param tempList
     * @param userId
     * @param orderId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result exportIn(List<ExcelTemp> tempList, Long userId, Long orderId) {
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(tempList)){
            throw new BusinessException(SystemError.FINANCE_ERROR_17036);
        }
   //     CustomizedOrder order = orderMapper.selectById(orderId);
        List<CustomizedOrderTouristInfo> list = new ArrayList<>();
        for (ExcelTemp temp : tempList) {
            CustomizedOrderTouristInfo touristInfo = EntityUtil.copy(temp,CustomizedOrderTouristInfo.class);
            //检查游客类型年龄范围
            if (touristInfo.getPackageId() != null){
                //自由报价
                TouristTypeDTO touristTypeDTO = touristTypeService.queryTouristType(touristInfo.getPackageId(),touristInfo.getMainDataId(), 1);
                if (touristTypeDTO != null){
                    //判断出生日期是否合理
                    if (!checkBirthday(touristInfo.getBirthday(),touristTypeDTO.getAgeBegin(),touristTypeDTO.getAgeEnd())){
                        throw new BusinessException(SystemError.CUSTOM_ORDER_4004);
                    }
                }
            }else{
                //行程报价
                TouristTypeDTO touristTypeDTO = touristTypeService.queryTouristType(touristInfo.getScheduleId(),touristInfo.getMainDataId(), 2);
                if (touristTypeDTO != null){
                    //判断出生日期是否合理
                    if (!checkBirthday(touristInfo.getBirthday(),touristTypeDTO.getAgeBegin(),touristTypeDTO.getAgeEnd())){
                        throw new BusinessException(SystemError.CUSTOM_ORDER_4004);
                    }
                }
            }
            //更新代收费用
            AddTouristTripScheduleDTO tripScheduleDTO = tripScheduleService.getAddTouristTripSchedule(touristInfo.getScheduleId(), touristInfo.getMainDataId());
            touristInfo.setCollectionFee(tripScheduleDTO.getColletionFee() == null?BigDecimal.ZERO:tripScheduleDTO.getColletionFee());
            List<TouristCollectionItemDTO> collectionItemList = tripScheduleDTO.getCollectionItemList();
            if (CollectionUtils.isNotEmpty(collectionItemList)){
                //旅客代收费用明细
                List<TouristCollectionFeeJson> collectionFeeJsonList = new ArrayList<>();
                for (TouristCollectionItemDTO itemDTO : collectionItemList){
                    TouristCollectionFeeJson collectionFeeJson = EntityUtil.copy(itemDTO,TouristCollectionFeeJson.class);
                    collectionFeeJson.setTotalAmount(itemDTO.getTotalAmount().multiply(itemDTO.getExchangeRate()));
                    collectionFeeJsonList.add(collectionFeeJson);
                }
                if (collectionFeeJsonList.size() > 0){
                    touristInfo.setCollectionFeeJson(JSON.toJSONString(collectionFeeJsonList));
                }
            }
            touristInfo.setModifiedId(userId);
            touristInfo.setIsFullInfo(1);
            list.add(touristInfo);
        }
        boolean batch = updateBatchById(list);
        if (!batch){
            throw new BusinessException(SystemError.SYS_411);
        }
        return Result.success();
    }

    /**
     * 导出旅客模板
     *
     * @param req
     * @return
     */
    @Override
    public ExcelData exportOut(CustomOrderIdReq req) {
        //旅客列表
        QueryWrapper<CustomizedOrderTouristInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id",req.getId());
        queryWrapper.eq("is_deleted",0);
        List<CustomizedOrderTouristInfo> touristInfoList = orderTouristInfoMapper.selectList(queryWrapper);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(touristInfoList)){
            ExcelData data = new ExcelData();
            data.setName(req.getId().toString());
            List<List<String>> title = new ArrayList();
            //设置Excel表头
            List<String> remark = setExcelHeaderRemark();
            List<String> header = setExcelHeader();
            //设置数据
            List<List<Object>> rows = new ArrayList();
            for (CustomizedOrderTouristInfo touristInfo : touristInfoList) {
                //筛选过滤
                List<Object> row = setRow(touristInfo);
                rows.add(row);
            }
            if (rows.size() == 0){
                throw new BusinessException(SystemError.FINANCE_BILL_17023);
            }

            title.add(remark);
            title.add(header);
            data.setTitles(title);
            data.setRows(rows);

            return data;
        }
        return null;
    }

    /**
     * 设置数据
     * @param touristInfo
     * @return
     */
    private List<Object> setRow(CustomizedOrderTouristInfo touristInfo) {
        List<Object> row = new ArrayList();
        row.add(touristInfo.getId());
        row.add(touristInfo.getTouristTypeName());
        row.add(touristInfo.getCnSurname());
        row.add(touristInfo.getCnName());
        row.add(touristInfo.getEnSurname());
        row.add(touristInfo.getEnName());
        String gender = getGender(touristInfo.getGender());
        row.add(gender);
        row.add(touristInfo.getMobileAreaCode());
        row.add(touristInfo.getMobile());
        if (touristInfo.getBirthday() != null){
            row.add(DateUtil.fmtLocalDate(touristInfo.getBirthday(),"yyyyMMdd"));
        }else{
            row.add("");
        }
        row.add(touristInfo.getNation());
        row.add(touristInfo.getEmail());
        row.add(touristInfo.getRemark());
        row.add(touristInfo.getCertificateType());
        row.add(touristInfo.getCertificateNumber());
        if (touristInfo.getCertificateValidDate() != null){
            row.add(DateUtil.fmtLocalDate(touristInfo.getCertificateValidDate(),"yyyyMMdd"));
        }else{
            row.add("");
        }
        row.add(touristInfo.getCertificatePlace());
        row.add(touristInfo.getCertificateType2());
        row.add(touristInfo.getCertificateNumber2());
        if (touristInfo.getCertificateValidDate2() != null){
            row.add(DateUtil.fmtLocalDate(touristInfo.getCertificateValidDate2(),"yyyyMMdd"));
        }else{
            row.add("");
        }
        row.add(touristInfo.getCertificatePlace2());
        row.add(touristInfo.getCertificateType3());
        row.add(touristInfo.getCertificateNumber3());
        if (touristInfo.getCertificateValidDate3() != null){
            row.add(DateUtil.fmtLocalDate(touristInfo.getCertificateValidDate3(),"yyyyMMdd"));
        }else{
            row.add("");
        }
        row.add(touristInfo.getCertificatePlace3());
        row.add(touristInfo.getEmergencyContactName());
        row.add(touristInfo.getEmergencyMobileAreaCode());
        row.add(touristInfo.getEmergencyMobile());
        return row;
    }

    /**
     * 获取称谓
     * @param gender
     * @return
     */
    private String getGender(Integer gender) {
        if (gender != null){
            if (Objects.equals(gender,1)){
                return "先生";
            }else if (Objects.equals(gender,2)){
                return "女士";
            }else if (Objects.equals(gender,3)){
                return "小姐";
            }else if (Objects.equals(gender,4)){
                return "男童";
            }else if (Objects.equals(gender,5)){
                return "女童";
            }
        }
        return null;
    }

    /**
     * 设置表头注释
     * @return
     */
    private List<String> setExcelHeaderRemark() {
        List<String> header = new ArrayList();
        header.add("此字段不要修改");
        header.add("此字段不要修改");
        header.add("");
        header.add("");
        header.add("");
        header.add("");
        header.add("請輸入“先生/女生/小姐/男童/女童”");
        header.add("例如：+852");
        header.add("");
        header.add("格式：19980101");
        header.add("");
        header.add("");
        header.add("");
        header.add("");
        header.add("");
        header.add("格式：19980101");
        header.add("");
        header.add("");
        header.add("");
        header.add("格式：19980101");
        header.add("");
        header.add("");
        header.add("");
        header.add("格式：19980101");
        header.add("");
        header.add("");
        header.add("例如：+852");
        header.add("");
        return header;
    }

    /**
     * 设置表头
     * @return
     */
    private List<String> setExcelHeader() {
        List<String> header = new ArrayList();
        header.add("ID");
        header.add("*旅客類型");
        header.add("*中文姓");
        header.add("*中文名");
        header.add("*英文姓");
        header.add("*英文名");
        header.add("*稱謂");
        header.add("*手機區號");
        header.add("*電話號碼");
        header.add("*出生日期");
        header.add("國籍");
        header.add("Email");
        header.add("備註");
        header.add("證件類型1");
        header.add("證件號碼1");
        header.add("證件有效期1");
        header.add("證件簽發地1");
        header.add("證件類型2");
        header.add("證件號碼2");
        header.add("證件有效期2");
        header.add("證件簽發地2");
        header.add("證件類型3");
        header.add("證件號碼3");
        header.add("證件有效期3");
        header.add("證件簽發地3");
        header.add("緊急聯絡人姓名");
        header.add("緊急聯絡手機區號");
        header.add("紧急聯絡電話號碼");
        return header;
    }


}
